package com.zrwl.poscloud.core.restapi.admin.baseInfo;
import com.zrwl.poscloud.base.entity.Grade;
import com.zrwl.poscloud.base.entity.StudentScoreBath;
import com.zrwl.poscloud.base.entity.SysDictData;
import com.zrwl.poscloud.commons.utils.*;
import com.zrwl.poscloud.core.annotion.AuthorityVerify.AuthorityVerify;
import com.zrwl.poscloud.core.annotion.OperationLogger.OperationLogger;
import com.zrwl.poscloud.commons.exception.ThrowableUtils;
import com.zrwl.poscloud.commons.validator.group.Delete;
import com.zrwl.poscloud.commons.validator.group.GetList;
import com.zrwl.poscloud.commons.validator.group.Insert;
import com.zrwl.poscloud.commons.validator.group.Update;
import com.zrwl.poscloud.xo.service.*;
import com.zrwl.poscloud.xo.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 教师 controller api类
 *
 * @author 刘思童 AutoGenerate
 * @date 2023-02-27
 */
@RestController
@Api(value = "教师相关接口", tags = {"教师相关接口"})
@RequestMapping("/gradeTeacherR")
@Slf4j
public class GradeTeacherRRestApi {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DeptAdminRService deptAdminRService;
    @Autowired
    private GradeTeacherRService gradeTeacherRService;
    @Autowired
    private GradeService gradeService;
    @Autowired
    private SysDictDataService sysDictDataService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private TeacherAdminRService teacherAdminRService;
    @AuthorityVerify
    @ApiOperation(value = "获取教师列表", notes = "获取教师列表", response = String.class)
    @PostMapping("/getList")
    public String getList(@Validated({GetList.class}) @RequestBody GradeTeacherRVO gradeTeacherRVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("获取教师列表: {}", gradeTeacherRVO);
        return ResultUtil.successWithData(gradeTeacherRService.getPageList(gradeTeacherRVO));
    }
    @AuthorityVerify
    @ApiOperation(value = "获取历史记录列表", notes = "获取历史记录列表", response = String.class)
    @PostMapping("/getHistoryRecordList")
    public String getHistoryRecordList(@Validated({GetList.class}) @RequestBody GradeTeacherRVO gradeTeacherRVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("获取历史记录列表: {}", gradeTeacherRVO);
        return ResultUtil.successWithData(gradeTeacherRService.getHistoryRecordList(gradeTeacherRVO));
    }
    @AuthorityVerify
    @ApiOperation(value = "获取教师列表", notes = "获取教师列表", response = String.class)
    @PostMapping("/getAllList")
    public String getAllList(@Validated({GetList.class}) @RequestBody GradeTeacherRVO gradeTeacherRVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("获取教师列表: {}", gradeTeacherRVO);
/*        AdminVO adminVO=adminService.getMe();
        TeacherAdminRVO teacherAdminRVO = teacherAdminRService.getTeacherByAdminUid(adminVO.getUid());
        if (teacherAdminRVO!=null){
            gradeTeacherRVO.setEmployeeUid(teacherAdminRVO.getEmployeeUid());
        }*/
        return ResultUtil.successWithData(gradeTeacherRService.getAllList(gradeTeacherRVO));
    }
    @AuthorityVerify
    @OperationLogger(value = "新增教师")    @ApiOperation(value = "新增教师", notes = "新增教师", response = String.class)
    @PostMapping("/add")
    public String add(@Validated({Insert.class}) @RequestBody GradeTeacherRVO gradeTeacherRVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("新增教师: {}", gradeTeacherRVO);
        return gradeTeacherRService.add(gradeTeacherRVO);
    }
    @AuthorityVerify
    @OperationLogger(value = "批量新增教师")    @ApiOperation(value = "批量新增教师", notes = "批量新增教师", response = String.class)
    @PostMapping("/batchAdd")
    public String batchAdd(@Validated({Insert.class}) @RequestBody List<GradeTeacherRVO> list, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("新增教师: {}", list);
        return gradeTeacherRService.batchAdd(list);
    }
    @AuthorityVerify
    @OperationLogger(value = "修改教师")    @ApiOperation(value = "修改教师", notes = "修改教师", response = String.class)
    @PostMapping("/edit")
    public String edit(@Validated({Update.class}) @RequestBody GradeTeacherRVO gradeTeacherRVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("修改教师: {}", gradeTeacherRVO);
        return gradeTeacherRService.edit(gradeTeacherRVO);
    }
    @AuthorityVerify
    @OperationLogger(value = "上传Excel")
    @ApiOperation(value = "上传Excel", notes = "上传Excel", response = String.class)
    @PostMapping("/uploadExcel")
    public String uploadExcel(@RequestParam("file") List<MultipartFile> file, @RequestParam("gradeUid") String gradeUid, @RequestParam("maxErrorData") int maxErrorData) {
        //1获取当前班级
        Grade grade = gradeService.getById(gradeUid);
        List<SysDictData> subjectTypeList = JsonUtils.jsonToList(JsonUtils.objectToJson(sysDictDataService.getListByDictType("subject_type").get("list")), SysDictData.class);
//2Excel解析并判重
        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < file.size(); i++) {
            MultipartFile fileO = file.get(i);
            if (fileO.isEmpty()) {
                continue;
            }
            list.addAll(ExcelUtil.ArrayList(file.get(i)));
        }
        Map<String, String> columnConfigMap = new HashMap<>();
        columnConfigMap.put("superDeptName","上级机构");
        columnConfigMap.put("gradeName", "班级");
        columnConfigMap.put("employeeName", "教师姓名(后缀)");
        List<GradeTeacherRVO> detailList = new LinkedList<>();//返回的错误数据
        /**
         * 遍历数据并进行校验
         */
        for (int i = 0; i < list.size(); i++) {
            GradeTeacherRVO gradeTeacherRVO = new GradeTeacherRVO();
            gradeTeacherRVO.setGradeUid(gradeUid);
            if (list.get(i).size() == 0) {
                continue;
            }
            Map<String, String> row = list.get(i);
            //赋值给明细表
            for (Map.Entry<String, String> entry : columnConfigMap.entrySet()) {
                String name = entry.getValue();
                //赋值给明细表
                if (StringUtils.isNotEmpty(row.get(name)) && StringUtils.isNotEmpty(row.get(name).trim())) {
                    ClassUtil.setFieldValueByFieldName(entry.getKey(), gradeTeacherRVO, row.get(name));
                }
            }
            if (StringUtils.isNotEmpty(row.get("科目")) && StringUtils.isNotEmpty(row.get("科目").trim())) {
                assert subjectTypeList != null;
                for (SysDictData dictData : subjectTypeList) {
                    if (dictData.getDictLabel().equals(row.get("科目"))) {
                        gradeTeacherRVO.setSubjectType(Integer.parseInt(dictData.getDictValue()));
                    }

                    if(Integer.parseInt(dictData.getDictValue()) == 0){
                        if(StringUtils.isBlank(row.get("假条通知(开启/关闭)"))){
                            gradeTeacherRVO.setLeaveInform(0);
                        }else {
                            gradeTeacherRVO.setLeaveInform(row.get("假条通知(开启/关闭)").equals("开启")?1:0);
                        }
                        if(StringUtils.isBlank(row.get("假条审核(开启/关闭)"))){
                            gradeTeacherRVO.setLeaveInform(1);
                        }else {
                            gradeTeacherRVO.setLeaveInform(row.get("假条审核(开启/关闭)").equals("开启")?1:0);
                        }
                        if(StringUtils.isBlank(row.get("发布作业(开启/关闭)"))){
                            gradeTeacherRVO.setLeaveInform(0);
                        }else {
                            gradeTeacherRVO.setLeaveInform(row.get("发布作业(开启/关闭)").equals("开启")?1:0);
                        }
                    }else {
                        if(StringUtils.isBlank(row.get("假条通知(开启/关闭)"))){
                            gradeTeacherRVO.setLeaveInform(1);
                        }else {
                            gradeTeacherRVO.setLeaveInform(row.get("假条通知(开启/关闭)").equals("开启")?1:0);
                        }
                        if(StringUtils.isBlank(row.get("假条审核(开启/关闭)"))){
                            gradeTeacherRVO.setLeaveInform(0);
                        }else {
                            gradeTeacherRVO.setLeaveInform(row.get("假条审核(开启/关闭)").equals("开启")?1:0);
                        }
                        if(StringUtils.isBlank(row.get("发布作业(开启/关闭)"))){
                            gradeTeacherRVO.setLeaveInform(1);
                        }else {
                            gradeTeacherRVO.setLeaveInform(row.get("发布作业(开启/关闭)").equals("开启")?1:0);
                        }
                    }
                }
            }
            try {
                gradeTeacherRService.singleImport(gradeTeacherRVO,grade);
            }catch (RuntimeException e){
                gradeTeacherRVO.setSummary(e.getMessage());
                detailList.add(gradeTeacherRVO);
            }
            if (detailList.size() >= maxErrorData) {
                break;
            }
        }
        return ResultUtil.successWithDataAndMessage(detailList, "成功导入" + (maxErrorData > list.size() ? (list.size() - detailList.size()) : (detailList.size() == 0 ? list.size() : (maxErrorData - detailList.size()))) + "条数据，失败" + detailList.size() + "条数据！");
    }
    @AuthorityVerify
    @OperationLogger(value = "删除教师")    @ApiOperation(value = "删除教师", notes = "删除教师", response = String.class)
    @PostMapping("/delete")
    public String delete(@Validated({Delete.class}) @RequestBody GradeTeacherRVO gradeTeacherRVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("删除教师: {}", gradeTeacherRVO);
        return gradeTeacherRService.delete(gradeTeacherRVO);
    }
    @AuthorityVerify
    @ApiOperation(value = "获取班级的教师列表(去重)", notes = "获取班级的教师列表(去重)", response = String.class)
    @PostMapping("/getEmployeeTeacher")
    public String getEmployeeTeacher(@Validated({GetList.class}) @RequestBody GradeTeacherRVO gradeTeacherRVO, BindingResult result) {
        ThrowableUtils.checkParamArgument(result);
        log.info("获取班级的教师列表(去重): {}", gradeTeacherRVO);
        AdminVO adminVO = adminService.getMe();
        TeacherAdminRVO teacherAdminRVO = teacherAdminRService.getTeacherByAdminUid(adminVO.getUid());
        if (teacherAdminRVO!=null){
            gradeTeacherRVO.setEmployeeUid(teacherAdminRVO.getEmployeeUid());
        }
        return ResultUtil.successWithData(gradeTeacherRService.getEmployeeTeacher(gradeTeacherRVO));
    }

}
